#include <iostream>
#include <cstdio>
#include <unistd.h>
#include <pthread.h>

using namespace std;

void printTid(const char *name, const pthread_t &tid)
{
    printf("%s 正在运行， thread id: 0x%x\n", name, tid);
}

void *startRoutine(void *args)
{
    const char *name = static_cast<const char*>(args);
    int cnt = 5;
    while(true)
    {
         // cout << "线程正在运行..." << endl;
         printTid(name, pthread_self());
         sleep(1);
         if(!(cnt--))
         {
            // break;
            // int *p = nullptr;
            // *p = 100; // 野指针问题·
         }
    }
    cout << "线程退出了..." << endl; 
    // 1. 线程退出的方式，return
    // return (void*)111;
    // 2. 线程退出的方式，pthread_exit
    pthread_exit((void*)1111);
}

int main()
{
    pthread_t tid;
    int n = pthread_create(&tid, nullptr, startRoutine, (void*)"thread1");
    (void)n;

    sleep(3); // 代表main thread对应的工作
    // 3.线程退出的方式：给线程发送取消请求
    pthread_cancel(tid);
    cout << "new thread been canceled" << endl;

    //printTid(tid, pthread_self());
    // cout << "new thread id : " << tid << endl; // 线程ID

    // sleep(10);

    void *ret = nullptr;
    pthread_join(tid, &ret); // void **retval是一个输出型参数
    cout << "main thread join success, *ret: " << (long long)(ret) << endl;

    sleep(10);

    while(true)
    {
        printTid("main thread", pthread_self());
        // cout << "main thread 正在运行..." << endl;
        sleep(1);
    }

    return 0;
}